package sdk.pay.helper;

import android.content.Context;
import android.content.Intent;
import android.provider.Settings;
import android.text.TextUtils;
import sdk.pay.utils.PayLogUtil;

import java.io.File;

/**
 * Description: 开启无障碍服务帮助类
 * File: OpenAccessibilitySettingHelper.java
 * Author: Administrator
 * Create: 2018/11/18 0018 上午 11:27
 */
public class OpenAccessibilitySettingHelper {
    /**
     * 跳转到无障碍服务设置页面
     *
     * @param context 设备上下文
     */
    public static void jumpToSettingPage(Context context) {
        Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    /**
     * 判断是否有辅助功能权限
     *
     * @return true 已开启
     * false 未开启
     */
    public static boolean isAccessibilitySettingsOn(Context context, String className) {
        int accessibilityEnabled = 0;
        final String service = context.getPackageName() + File.separator + className;
        PayLogUtil.logBase("service = " + service);
        boolean accessibilityFound = false;
        try {
            accessibilityEnabled = Settings.Secure.getInt(
                    context.getApplicationContext().getContentResolver(),
                    android.provider.Settings.Secure.ACCESSIBILITY_ENABLED);
        } catch (Settings.SettingNotFoundException e) {

        }
        TextUtils.SimpleStringSplitter mStringColonSplitter = new TextUtils.SimpleStringSplitter(':');

        if (accessibilityEnabled == 1) {
            String settingValue = Settings.Secure.getString(
                    context.getApplicationContext().getContentResolver(),
                    Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
            if (settingValue != null) {
                TextUtils.SimpleStringSplitter splitter = mStringColonSplitter;
                splitter.setString(settingValue);
                while (splitter.hasNext()) {
                    String accessabilityService = splitter.next();
                    if (accessabilityService.equalsIgnoreCase(service)) {
                        return true;
                    }
                }
            }
        }

        return accessibilityFound;
    }

}
